<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/9/4
 * Time: 17:44
 */

declare (strict_types=1);

namespace app\service\traits;


use think\Exception;

trait Rely
{
    // 依赖包
    protected $rely;

    /**
     * 依赖管理
     *
     * @param string $name
     * @return object|string
     * @throws Exception
     */
    public function __get(string $name)
    {
        // 调用静态方法 getInstance
        $this->$name = method_exists($class = $this->getClassName($name), 'getInstance') ? call_user_func_array([$class, 'getInstance'], []) : $class;

        return $this->$name;
    }

    /**
     * 获取 class 的类名
     *
     * @param string $name
     * @return string
     * @throws Exception
     */
    protected function getClassName(string $name): string
    {
        // 异常处理
        if (!isset($this->rely[$name])) throw new Exception("Dependency $name does not exist.");

        return $this->rely[$name];
    }
}
